<?php

namespace app\controller\api\controller;

use app\popo\dto\EditPasswordRequest;
use app\popo\vo\EmployeeLoginVO;
use app\service\EmployeeService;
use app\support\JwtHelper;
use app\support\ResponseHelper;
use DI\Attribute\Inject;
use Illuminate\Support\Arr;
use Shayvmo\WebmanAnnotations\Annotations\GetMapping;
use Shayvmo\WebmanAnnotations\Annotations\PostMapping;
use Shayvmo\WebmanAnnotations\Annotations\PutMapping;
use Shayvmo\WebmanAnnotations\Annotations\RestController;
use support\Response;
use Webman\Http\Request;

#[RestController("/api/employee")]
class EmployeeController
{
    #[Inject]
    protected EmployeeService $employeeService;
    #[PostMapping(path: "/login")]
    public function login(Request $request): Response
    {
        $employee = $this->employeeService->login($request->all());
        $jwt = JwtHelper::generate($employee);
        $token = Arr::get($jwt, "access_token");

        $employeeLoginVo = EmployeeLoginVO::fromArray(array(
            "id" => $employee->id,
            "name" => $employee->name,
            "token" => $token,
            "userName" => $employee->username
        ));

        return  ResponseHelper::successJson($employeeLoginVo->toArray());
    }


    #[GetMapping(path: "/page")]
    public function list(Request $request): Response
    {
        $result = $this->employeeService->pageQuery($request->all());
        return  ResponseHelper::successJson($result);
    }

    #[PostMapping]
    public function addEmployee(Request $request): Response
    {
        $this->employeeService->save($request->all());
        return ResponseHelper::successJson();
    }

    #[GetMapping("/{id}")]
    public function employee(int $id): Response
    {
        $employee = $this->employeeService->getById($id);
        return ResponseHelper::successJson($employee->toViewData());
    }

    #[PostMapping("/status/{status}")]
    public function startOrStop(int $status, Request $request): Response
    {
        $this->employeeService->startOrStop($status, $request->get("id"));
        return ResponseHelper::successJson();
    }

    #[PutMapping]
    public function update(Request $request): Response
    {
        $this->employeeService->update($request->all());
        return ResponseHelper::successJson();
    }

    #[PostMapping("/logout")]
    public function logout(): Response
    {
        return ResponseHelper::successJson();
    }

    
    #[PutMapping("/editPassword")]
    /**
     * 更改密码
     */
    public function editPassword(EditPasswordRequest $request): Response
    {
        try {
            $this->employeeService->editPassword($request);
            return ResponseHelper::successJson();
        } catch (\Exception $e) {
            return ResponseHelper::failJson($e->getMessage());
        }

    }
}